﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Common.Json
{
    /// <summary>
    /// 字符串掩码,将字符串中的数字（连续三位以上）全部替换为星号（*）
    /// </summary>
    public class StringMaskConverter : JsonConverter
    {
        /// <summary>
        /// 是否能转换
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return typeof(string) == objectType;
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            return reader.Value;
        }
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (value == null)
            {
                return;
            }
            string str = value.ToString();
            string pattern = "[0123456789〇一二三四五六七八九零壹贰叁肆伍陆柒捌玖①②③④⑤⑥⑦⑧⑨]{5,}";
            string masked = Regex.Replace(str, pattern, "****");
            writer.WriteValue(masked);
        }
    }
}
